import {
  getProduceInfoByPage,
  addProduceInfo,
  updateProduceInfo,
  delProduceInfo,
  getStandProductCode,
  releaseProductInfo,
  getProduceType,
  getProjectTeamEngineers,
  addProductInfosByExcel,
  downloadExcelTemplate,
} from '@/services/project/produceInfo';
import { PlusOutlined, ArrowLeftOutlined, RiseOutlined, InboxOutlined, UploadOutlined } from '@ant-design/icons';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import type { ActionType, ProColumns } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { Button, Form, Input, message, Checkbox, Modal, Tree, Select, Tooltip, UploadProps, UploadFile, Upload } from 'antd';
import { sortTran, filterTran } from '@/utils/requestUtil';
import React, { useRef, useState } from 'react';
import { Ellipsis } from '@/components/Ellipsis';
import { history } from 'umi';
import { getStandProductByPage } from '@/services/design/standProduct';
import { getMaterialInfoByMaterialProperty } from '@/services/baseData/materialInfo';
import Dragger from 'antd/lib/upload/Dragger';
const ProduceInfo = React.forwardRef((props, ref) => {
  const actionRef = useRef<ActionType>();
  const [modalVisit, setModalVisit] = useState(false); // 新建和编辑提示框
  const [confirmLoading, setConfirmLoading] = useState(false); //编辑框的disable
  const [uploadConfirmLoading, setUploadConfirmLoading] = useState(false); //上传文件加载
  const [formTitle, setFormTitle] = useState('新建'); //
  const [createOrUpdate, setCreateOrUpdate] = useState(false); //编辑框的disable
  const [form] = Form.useForm();
  const [isStand, setIsStand] = useState(false);
  const [allTypeOptions, setAlltypeOptions] = useState([]);
  const refs = useRef(null);
  const [selectedRowKeys, setSelectedRowKeys] = useState<React.Key[]>([]);
  const [productCode, setProductCode] = useState([]);
  const [descAndCode, setDescAndCode] = useState([]);
  const [page, setPage] = useState<number>(1);
  const [enginner, setenginner] = useState([]);
  const [materialCodeOptions, setMaterialCodeOptions] = useState([]);
  const [materialCodeToName, setMaterialCodeToName] = useState([]);
  const [modalVisit2, setModalVisit2] = useState(false); //导入提示框
  const [file, setFile] = useState<UploadFile[]>(); //导入的文件
  const fileTypeList = ['xlsx', 'xls']; //设定的允许上传文件数组

  ProduceInfo.defaultProps = {
    produceFlag: true,
    infosId: '',
  };
  const produceFlag = props.produceFlag;
  const infosId = props.produceInfoId;
  const stateType = ['未下发', '设计中', '工单下发', '生产中', '暂停'];
  const reviewStateType = ['待上传', '待审核', '审核通过'];

  React.useImperativeHandle(ref, () => ({
    update() {
      actionRef.current?.reload();
    },
  }));

  const columns: ProColumns[] = [
    {
      title: '序号',
      dataIndex: 'index',
      valueType: 'index',
      width: 40,
      render: (text, record, index) => (page - 1) * 100 + index + 1,
    },
    {
      title: '柜体编号',
      dataIndex: 'productCode',
      width: 120,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '柜体类型',
      dataIndex: 'productType',
      width: 70,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
      filters: true,
      onFilter: true,
      ellipsis: true,
      valueType: 'select',
      //有空需要改成动态数据
      valueEnum: {
        安装板: {
          text: '安装板',
        },
        箱体: {
          text: '箱体',
        },
        柜体: {
          text: '柜体',
        },
        其他: {
          text: '其他',
        },
      },
    },
    {
      title: '是否发布',
      dataIndex: 'isPublished',
      width: 50,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '标准柜体',
      dataIndex: 'isStandard',
      width: 50,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '柜体状态',
      dataIndex: 'state',
      width: 50,
      align: 'center',
      sorter: true,
      render: (text) => <div>{text === -1 ? '暂停' : stateType[text]}</div>,
    },
    {
      title: '审核状态',
      dataIndex: 'reviewState',
      width: 50,
      align: 'center',
      sorter: true,
      render: (text) => <div>{text === -1 ? '暂停' : reviewStateType[text]}</div>,
    },
    {
      title: '技术工程师',
      dataIndex: 'engineer',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '标准柜体编号',
      dataIndex: 'standTypeCode',
      width: 100,
      align: 'center',
      sorter: true,
      search: false,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '物料编号',
      dataIndex: 'materialCode',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '物料名称',
      dataIndex: 'materialName',
      width: 100,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '柜体描述',
      dataIndex: 'productDesc',
      width: 80,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '备注',
      dataIndex: 'memo',
      width: 80,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '创建日期', //表头显示的名称
      search: false,
      dataIndex: 'createTime',
      width: 65,
      align: 'center',
      sorter: true,

      render: (text) => <>{Ellipsis(text)}</>,
    },

    {
      title: '创建人',
      dataIndex: 'createName',
      width: 50,
      align: 'center',
      sorter: true,
      render: (text) => <>{Ellipsis(text)}</>,
    },
    {
      title: '操作',
      valueType: 'option',
      key: 'option',
      width: 50,
      align: 'center',
      fixed: 'right',
      render: (text, record, _, action) => [
        <a
          key="deleteKey"
          onClick={() => {
            Modal.confirm({
              title: '删除',
              content: '确定要删除吗',
              okText: '确认',
              cancelText: '取消',
              onOk: async () => {
                const result = await delProduceInfo({ id: record.id });
                if (result !== null && result != undefined) {
                  if (result.code === 0) {
                    message.success('删除成功');
                  }
                }
                actionRef.current!.reload();
              },
            });
          }}
        >
          删除
        </a>,
      ],
    },
  ];
  const handleSubmit = async () => {
    setConfirmLoading(true);
    if (formTitle == '新建') {
      form
        .validateFields()
        .then(async (value) => {
          let resTemp;
          if (infosId) {
            resTemp = { ...form.getFieldsValue(), infoId: infosId };
          } else {
            resTemp = { ...form.getFieldsValue(), infoId: history.location.state.id };
          }
          resTemp.standTypeCode = resTemp.standTypeCode.split('——')[0];
          resTemp.productQty = Number(resTemp.productQty);
          resTemp.isStandard = Number(resTemp.isStandard);
          // console.log(resTemp, '新建参数');
          const result = await addProduceInfo(resTemp);
          if (result != null) {
            message.success('添加成功');
          }
          setConfirmLoading(false);
          setModalVisit(false);
          actionRef.current!.reload();
        })
        .catch((err) => {
          console.log(err, '出错了...');
          setConfirmLoading(false);
        });
    } else {
      let resTemp;
      if (infosId) {
        resTemp = { ...form.getFieldsValue(), infoId: infosId };
      } else {
        resTemp = { ...form.getFieldsValue(), infoId: history.location.state.id };
      }
      resTemp.isStandard = Number(resTemp.isStandard);
      if (resTemp.isStandard === '是') {
        resTemp.isStandard = 1;
      } else {
        resTemp.isStandard = 0;
      }
      const result = await updateProduceInfo(resTemp);
      if (result != null) {
        message.success('编辑成功');
      }
      setConfirmLoading(false);
      setModalVisit(false);
      actionRef.current!.reload();
    }
  };

  //获取所有柜体类型+柜体编号
  const allProductType = async () => {
    const res = await getProduceType(null);
    const temp: any[] = [];
    if (res && res.data) {
      res.data.map((item: any) => {
        temp.push({ value: item, label: item });
      });
    }
    setAlltypeOptions(temp);
    // 获取工程师
    console.log(infosId, 'infosId');
    const getresult = await getProjectTeamEngineers(infosId);
    const engineers: any[] = [];
    getresult.data.map((item: any, index: any) => {
      engineers.push({ value: item, label: item });
    });
    setenginner(engineers);
  };

  //选中selection中的序号
  const onSelectChange = (newSelectedRowKeys: React.Key[]) => {
    setSelectedRowKeys(newSelectedRowKeys);
  };

  //发布单条柜体信息
  const releaseProduct = async () => {
    if (selectedRowKeys.length !== 0) {
      const result = await releaseProductInfo(selectedRowKeys);
      if (result != null) {
        message.success('发布成功');
      }
      actionRef.current?.reload();
    } else {
      message.info('请先选中您要发布的柜体信息!');
    }
  };

  const handlePageChange = (e: any) => {
    setPage(e);
  };

  //获取物料编号的下拉框内容
  const getMaterialCodeOptions = async () => {
    const result = await getMaterialInfoByMaterialProperty('产成品');
    console.log(result, '产成品');
    let tempOptions: { value: string; label: string }[] = [];
    let tempCodeToName: { materialInfoId: string; materialCode: string; materialName: string }[] =
      [];
    result.data.map((item: any) => {
      tempOptions.push({ value: item.materialCode, label: item.materialCode });
      tempCodeToName.push({
        materialInfoId: item.id,
        materialCode: item.materialCode,
        materialName: item.materialName,
      });
    });
    setMaterialCodeToName(tempCodeToName);
    setMaterialCodeOptions(tempOptions);
  };

  //将upload组件的文件保存在file中
  const onFilesChange: UploadProps['onChange'] = (info: any) => {
    let newFile = [...info.fileList];
    newFile = newFile.splice(-1); //限制上传个数
    const fileType = info.file.name.split('.').pop();
    if (fileTypeList.indexOf(fileType) != -1) {
      setFile(newFile);
    }
    /*     if(fileType === 'xlsx' || fileType === 'xls'){
      setFile(newFile);
    } */
  };

  //选择文件后检验
  const beforeUpload = (file: any) => {
    const fileType = file.name.split('.').pop();
    if (fileTypeList.indexOf(fileType) === -1) {
      message.error('上传失败：上传文件格式不正确');
    }
    /*     if (fileType !== 'xlsx' && fileType !== 'xls') {
      message.error(`上传失败：上传文件格式不正确`);
    } */
    return false;
  };

  //批量导入柜体信息
  const handleUpload = async () => {
    setUploadConfirmLoading(true);
    const formData = new FormData();
    //如果没有选择文件
    if (file === void 0) {
      message.error('请选择文件');
      return;
    }
    formData.append('file', file[0].originFileObj);
    console.log(formData, '要上传的文件');
    console.log(infosId, '要上传的文件');
    const result = await addProductInfosByExcel({ file: formData, infoId: infosId });
    if (result && result.code === 0) {
      message.success('导入成功');
    } else message.error('导入失败');
    setUploadConfirmLoading(false);
    actionRef.current?.reload();
    setFile([]); //清空文件
    setModalVisit2(false);
  };

    //下载模板
    const handleDownload = () => {
      downloadExcelTemplate().then((result) => {
        const aLink = document.createElement('a');
        document.body.appendChild(aLink);
        aLink.style.display = 'none';
        aLink.href = window.URL.createObjectURL(result);
        aLink.setAttribute('download', `柜体导入模板.xls`);
        aLink.click();
        document.body.removeChild(aLink);
      });
    };

  return (
    <PageHeaderWrapper title={false} breadcrumb={undefined}>
      <ProTable
        headerTitle="柜体信息查询"
        actionRef={actionRef} //用于触发刷新操作等，看api
        rowKey="id" //表格行 key s的取值，可以是字符串或一个函数
        formRef={refs}
        columnsState={{
          defaultValue: {
            createName: {
              show: false,
            },
          },
        }}
        columns={columns}
        toolBarRender={(action, { selectedRows }) => [
          <Button
          key="button"
          onClick={handleDownload}
          type="primary"
        >
          模板下载
        </Button>,
          <Button
            key="button"
            onClick={() => setModalVisit2(true)}
            type="primary"
          >
            批量导入柜体信息
        </Button>,
          <Button
            key="button"
            icon={<ArrowLeftOutlined />}
            onClick={() => {
              history.push('/project/info');
            }}
            type="primary"
          >
            返回
          </Button>,
          // <Button
          //   key="button"
          //   icon={<RiseOutlined />}
          //   onClick={() => {
          //     releaseProduct();
          //   }}
          //   type="primary"
          // >
          //   发布
          // </Button>,
          <Button
            key="button"
            icon={<PlusOutlined />}
            onClick={() => {
              setCreateOrUpdate(false);
              setFormTitle('新建');
              getMaterialCodeOptions(); //获取非标柜时物料编号的下拉框内容
              form.resetFields();
              setModalVisit(true);
            }}
            type="primary"
          >
            新建
          </Button>,
          // <Button
          //   key="button"
          //   icon={<PlusOutlined />}
          //   onClick={() => {
          //     const filters = filterTran(ref.current.getFieldsValue());
          //     exportProduceInfo({
          //       current: 1,
          //       pageSize: 5000,
          //       filters: filters,
          //     }).then((res) => {
          //       const aLink = document.createElement('a');
          //       document.body.appendChild(aLink);
          //       aLink.style.display = 'none';
          //       aLink.href = window.URL.createObjectURL(res);
          //       aLink.setAttribute('download', `ProduceInfo.xlsx`);
          //       aLink.click();
          //       document.body.removeChild(aLink);
          //     });
          //   }}
          //   type="primary"
          // >
          //   导出
          // </Button>,
        ]}
        request={async (params = {}, sort, filter) => {
          let res;
          if (produceFlag !== undefined && !produceFlag) {
            res = { ...params, infoId: infosId };
          } else {
            res = { ...params, infoId: history.location.state.id };
          }
          const sorters = sortTran(sort);
          const filters = filterTran(res);
          const result = await getProduceInfoByPage({
            ...params,
            sorters: sorters,
            filters: filters,
          });
          /*           const result1 = await getStandProductByPage({
            ...params,
            sorters: [],
            filters: [],
          }); */
          const content = result.data.content;
          content.map((item: any) => {
            if (item.isStandard == 1) {
              item.isStandard = '是';
            } else {
              item.isStandard = '否';
            }
            if (item.isPublished == 1) {
              item.isPublished = '是';
            } else {
              item.isPublished = '否';
            }
          });

          allProductType();
          return {
            data: content,
            total: result.data.totalElements,
            success: result.success,
          };
        }}
        scroll={{ x: 1000, y: 300 }}
        // search={produceFlag}
        rowSelection={{ onChange: onSelectChange }}
        pagination={{
          defaultPageSize: 100,
          pageSizeOptions: [],
          onChange: handlePageChange,
        }}
      />
      <Modal
        title={formTitle}
        open={modalVisit}
        onOk={handleSubmit}
        confirmLoading={confirmLoading}
        onCancel={() => setModalVisit(false)}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item label="id" name="id" hidden={true}>
            <Input />
          </Form.Item>
          <Form.Item
            label="标准柜体"
            name="isStandard"
            rules={[{ required: true, message: '请选择是否为标准柜体！' }]}
          >
            <Select
              disabled={createOrUpdate}
              placeholder="是否为标准柜体"
              onChange={(value: any) => {
                if (value === '1') {
                  setIsStand(false);
                } else {
                  setIsStand(true);
                }
                form.setFieldsValue({
                  standTypeCode: '',
                  productDesc: '',
                  materialName: '',
                  materialCode: '',
                });
              }}
              options={[
                { value: '1', label: '是' },
                { value: '0', label: '否' },
              ]}
            />
          </Form.Item>
          <Form.Item
            label="柜体类型"
            name="productType"
            rules={[{ required: true, message: '请选择柜体类型' }]}
          >
            <Select
              placeholder="请选择柜体类型"
              onChange={async (value, params = {}, sort, filter) => {
                form.setFieldsValue({
                  standTypeCode: '',
                  productDesc: '',
                  materialName: '',
                  materialCode: '',
                });
                let codeTemp: any[] = [];
                const code: any[] = [];
                const allCode = await getStandProductCode(null);
                console.log(allCode, 'all');
                if (value === '安装板') {
                  codeTemp = allCode.data['安装板'];
                } else if (value === '柜体') {
                  codeTemp = allCode.data['柜体'];
                } else if (value === '箱体') {
                  codeTemp = allCode.data['箱体'];
                } else if (value === '其他') {
                  codeTemp = allCode.data['其他'];
                } else {
                  codeTemp = allCode.data['其他'];
                }
                codeTemp.map((item: any) => {
                  code.push({
                    value: item.standTypeCode + '——' + item.productDesc,
                    label: item.standTypeCode + '——' + item.productDesc,
                  });
                });
                setDescAndCode(codeTemp);
                setProductCode(code);
              }}
              options={allTypeOptions}
            />
          </Form.Item>
          <Form.Item
            label="标准柜体编号"
            name="standTypeCode"
            hidden={isStand}
            rules={[{ required: !isStand && true, message: '请选择柜体编号！' }]}
          >
            <Select
              showSearch
              placeholder="请选择柜体编号"
              disabled={createOrUpdate}
              onChange={(value) => {
                const temp = value.split('——')[0];
                const TempItem = descAndCode.find((item) => item?.standTypeCode == temp) || '';
                form.setFieldsValue({
                  productDesc: TempItem.productDesc,
                  materialCode: TempItem.materialCode,
                  materialName: TempItem.materialName,
                });
              }}
              options={productCode}
            />
          </Form.Item>
          <Form.Item label="&nbsp;&nbsp;&nbsp;柜体描述" name="productDesc">
            <Input disabled={!isStand} placeholder="请输入柜体描述" />
          </Form.Item>
          <Form.Item
            label="柜体数量"
            name="productQty"
            hidden={createOrUpdate}
            rules={[
              { required: true, message: '请输入柜体数量！' },
              {
                pattern: /^[1-9][0-9]{0,}$/,
                message: '柜体数量格式不对',
                validateTrigger: ['onBlur', 'onChange'],
              },
            ]}
          >
            <Input />
          </Form.Item>
          <Form.Item
            label="&nbsp;&nbsp;&nbsp;物料编号"
            name="materialCode"
          /*             rules={[{ required: true, message: '请选择物料编号！' }]} */
          >
            <Select
              showSearch
              placeholder="请选择物料编号"
              disabled={!isStand}
              onChange={(value) => {
                console.log(materialCodeToName, 'materialCodeName');
                let data = materialCodeToName.find((item: any) => item.materialCode === value);
                form.setFieldsValue({
                  materialName: data?.materialName,
                });
              }}
              options={materialCodeOptions}
            />
          </Form.Item>
          <Form.Item label="&nbsp;&nbsp;&nbsp;物料名称" name="materialName">
            <Input disabled />
          </Form.Item>
          <Form.Item
            label="技术工程师"
            name="engineer"
            hidden={!isStand}
            rules={[{ required: isStand, message: '请选择技术工程师!' }]}
          >
            <Select placeholder="请选择技术工程师" onChange={() => { }} options={enginner} />
          </Form.Item>
          <Form.Item
            label="项目id"
            name="infoId"
            hidden={true}
          //rules={[{ required: true, message: 'Please input your infoId!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item
            label="项目名称"
            name="projectName"
            hidden={true}
          //rules={[{ required: true, message: 'Please input your projectName!' }]}
          >
            <Input disabled={createOrUpdate} />
          </Form.Item>
          <Form.Item label="&nbsp;&nbsp;&nbsp;备注" name="memo">
            <Input />
          </Form.Item>
        </Form>
      </Modal>
      {/* 导入窗口 */}
      <Modal
        title="导入"
        visible={modalVisit2}
        confirmLoading={uploadConfirmLoading}
        onOk={handleUpload}
        onCancel={() => {
          setModalVisit2(false);
          setFile([]); //清空文件
        }}
      >
        <Form
          name="wrap"
          labelCol={{ flex: '110px' }}
          labelAlign="left"
          labelWrap
          form={form}
          wrapperCol={{ flex: 1 }}
          colon={false}
        >
          <Form.Item
            label="上传文件"
            name="file"
            rules={[{ required: true, message: '请上传工时周期文件!' }]}
          >
            <Upload
              accept={'.xlsx,.xls'}
              listType="picture"
              fileList={file}
              onChange={onFilesChange} //通过覆盖默认的上传行为，可以自定义自己的上传实现
              showUploadList={true}
              beforeUpload={beforeUpload}
            >
              <Button icon={<UploadOutlined />}>上传文件</Button>
            </Upload>
          </Form.Item>
        </Form>
      </Modal>
    </PageHeaderWrapper>
  );
});
export default ProduceInfo;
